package com.jprocms.module.cms.controller.directive;

import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.module.system.api.dict.DictDataApi;
import com.jpro.module.system.api.dict.dto.DictDataRespDTO;
import com.jprocms.module.cms.cache.MyRedisHelper;
import com.jprocms.module.cms.util.Freemarkers;
import com.jprocms.module.cms.web.Directives;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static com.jprocms.module.cms.dal.redis.RedisKeyConstants.DICT_DATA;

/**
 * 字典列表 自定义标签
 *
 * @author jprocms
 */
public class DictListDirective implements TemplateDirectiveModel {
    /**
     * 类型别名。字符串（String）。
     */
    private static final String TYPE = "type";

    @SuppressWarnings("unchecked")
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        Freemarkers.requireLoopVars(loopVars);
        Freemarkers.requireBody(body);

        String typeAlias = Directives.getString(params, TYPE);
        final Object typeAliasCache = redisHelper.hget(DICT_DATA, typeAlias);
        List<DictDataRespDTO> list;
        if (typeAliasCache != null && typeAliasCache instanceof List) {
            list = (List<DictDataRespDTO>) typeAliasCache;
        } else {
            CommonResult<List<DictDataRespDTO>> dictDataByTypeResp = dictDataApi.getDictDataByType(typeAlias);
            list = Collections.emptyList();
            if (!dictDataByTypeResp.isError()) {
                list = dictDataByTypeResp.getData();
                //缓存10分钟
                redisHelper.hset(DICT_DATA, typeAlias, list, 600);
            }
        }
        loopVars[0] = env.getObjectWrapper().wrap(list);
        body.render(env.getOut());
    }


    private final DictDataApi dictDataApi;
    private MyRedisHelper redisHelper;

    public DictListDirective(DictDataApi dictDataApi, MyRedisHelper redisHelper) {
        this.dictDataApi = dictDataApi;
        this.redisHelper = redisHelper;
    }
}
